<template>
  <view class="categorize">
    <view class="categorize-top">
      <my-searchbar
        v-model="query.search"
        placeholder="搜索商品名称/条形码"
        @search="fetchGoodsList(true)"
      ></my-searchbar>
      <my-filterbar
        v-model:price="priceSort"
        v-model:number="numberSort"
        @filter="popupShow = true"
      ></my-filterbar>
    </view>

    <view class="categorize-content">
      <my-category
        :height="184"
        :list="categoryList"
        v-model="current"
        @switchCurrent="handleSwitchCurrent"
        @scrolltolower="handleScrolltolower"
        @detail="toCategoryDetail"
      >
        <template v-if="list.length">
          <view
            v-for="item in list"
            :key="item.id"
            style="margin-bottom: 20rpx; padding: 0 10rpx"
          >
            <my-goods :data="item" @addCart="handleAddCart(item)"></my-goods>
          </view>
        </template>
        <template v-else>
          <my-empty text="暂无数据"></my-empty>
        </template>
      </my-category>
    </view>

    <u-popup :show="popupShow" mode="right" @close="popupShow = false">
      <view class="popup-content">
        <view class="price">
          <u-text text="价格" bold size="24"></u-text>
          <view class="input">
            <u-input
              type="number"
              v-model="query.sale_price__gte"
              placeholder="最低价"
            ></u-input>
            <u-line length="15%" margin="10px"></u-line>
            <u-input
              type="number"
              v-model="query.sale_price__lte"
              placeholder="最高价"
            ></u-input>
          </view>
        </view>
        <view class="pp">
          <view>
            <u-text text="品牌" bold size="24"></u-text>
          </view>
          <view class="input">
            <view
              :class="['item', currentBrand.includes(item.id) ? 'active' : '']"
              v-for="(item, index) in brands"
              :key="index"
              @click="handleChangeBrand(item)"
            >
              {{ item.name }}
            </view>
          </view>
        </view>
        <view class="actions">
          <view class="item">
            <u-button type="primary" plain @click="popupShow = false"
              >关闭</u-button
            >
          </view>
          <view class="item">
            <u-button type="primary" @click="handleFilterConfirm"
              >确认</u-button
            >
          </view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script setup>
import { reactive, ref, toRef, watch } from "vue";
import { categories, goodsList } from "@/common/apis/goods.js";
// import { supplierList } from "@/common/apis/supplier.js";
import { brandList } from "@/common/apis/brand.js";
import { onShow } from "@dcloudio/uni-app";
import { useStore } from "vuex";

const store = useStore();

const priceSort = ref(true);

const numberSort = ref(true);

const sortList = ref(["id", "sale_price", "sale_number"]);

watch(
  () => priceSort.value,
  (newVal) => {
    if (newVal) {
      sortList.value[1] = "sale_price";
    } else {
      sortList.value[1] = "-sale_price";
    }
  }
);

watch(
  () => numberSort.value,
  (newVal) => {
    if (newVal) {
      sortList.value[2] = "sale_number";
    } else {
      sortList.value[2] = "-sale_number";
    }
  }
);

// 商品列表请求参数
const query = reactive({
  search: "",
  sale_price__gte: "",
  sale_price__lte: "",
  brand__in: "",
  category: undefined,
  ordering: toRef(() => JSON.stringify(sortList.value)),
  page: 1,
  size: 20,
});

const popupShow = ref(false);

// 分类组件高度
const categoryHeight = ref(660);

// 分类列表
const categoryList = ref([]);

// 当前分类索引
const current = ref(0);

// 商品列表
const list = ref([]);

// 总页数
const totalPage = ref(0);

const brands = ref([]);

const currentBrand = ref([]);

watch([() => priceSort.value, () => numberSort.value], () => {
  fetchGoodsList(true);
});

watch(
  () => current.value,
  (newVal) => {
    query.category = categoryList.value[newVal].id;
    fetchGoodsList(true);
  }
);

// 获取供应商列表
async function fetchBrandList() {
  const response = await brandList();
  if (response) {
    brands.value = response;
  }
}

// 获取商品分类列表
async function fetchCategories() {
  const response = await categories({
    all: "1",
  });
  if (response) {
    categoryList.value = [
      {
        name: "全部商品",
      },
      ...response,
    ];
  }
}

/**
 * @description 获取商品列表
 * @param {Boolean} isCover 赋值时是否重新覆盖
 */
async function fetchGoodsList(isCover = false) {
  uni.showLoading();
  const response = await goodsList(query);
  uni.hideLoading();
  if (response) {
    // 总页数
    totalPage.value = response.total_page;
    if (isCover) {
      list.value = response.records;
    } else {
      list.value = list.value.concat(response.records);
    }
  }
}

// 切换当前
function handleSwitchCurrent(e) {
  console.log(e);
}

// 滚动到底部
async function handleScrolltolower() {
  if (query.page < totalPage.value) {
    query.page += 1;
    await fetchGoodsList(false);
  }
}

// 切换排序方式
async function handleSwitchOrdering() {
  if (query.ordering == "id") {
    query.ordering = "-id";
  } else {
    query.ordering = "id";
  }
  await fetchGoodsList(true);
}

// 供应商change事件
function handleChangeBrand(item) {
  if (currentBrand.value.includes(item.id)) {
    const index = currentBrand.value.findIndex((i) => i == item.id);
    currentBrand.value.splice(index, 1);
  } else {
    currentBrand.value.push(item.id);
  }
}

// 确认筛选
async function handleFilterConfirm() {
  query.brand__in = currentBrand.value.join(",");
  await fetchGoodsList(true);
  popupShow.value = false;
}
// 添加到购物车
async function handleAddCart(i) {
  await store.dispatch("fetchAddCart", {
    product_id: i.id,
    quantity: 1,
  });
}

// 前往该分类商品详情
function toCategoryDetail(data) {
  console.log(data);
}

onShow(async () => {
  // 获取分类列表
  await fetchCategories();
  // 商品列表赋值分类id
  query.category = categoryList.value[current.value].id;
  // 获取商品列表
  await fetchGoodsList(true);
  // 获取供应商列表
  await fetchBrandList();
  // uni.getSystemInfo({
  //   success: (res) => {
  //     categoryHeight.value = res.windowHeight - 120;
  //   },
  // });
});
</script>

<style lang="scss" scoped>
.categorize {
  background-color: #f1f1f1;
  display: flex;
  flex-direction: column;

  .categorize-top {
    height: 184rpx;
    padding: 20rpx 20rpx 0;
    background-color: #ffffff;
    border-bottom: 2rpx solid #f0f0f0;
    box-sizing: border-box;
  }

  .categorize-content {
    height: calc(100vh - 184rpx);
    overflow: hidden;
  }
}

.search-bar {
  margin-top: 20rpx;
  padding: 0 20rpx;
  display: flex;
  align-items: center;

  .center {
    flex: 1;
    margin: 0 20rpx;
  }

  .right {
    display: flex;
    align-items: center;

    .text {
      margin-left: 10rpx;
      width: 2em;
      font-size: 24rpx;
    }
  }
}

.filter-bar {
  margin: 0 20rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-radius: 10rpx;
  background-color: #fff;
  box-shadow: 0 0 10px 1px rgba(0, 0, 0, 0.1);
  padding: 20rpx;
}

.popup-content {
  width: 600rpx;
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 40rpx;
  box-sizing: border-box;

  .price {
    .input {
      padding: 40rpx 0;
      display: flex;
      align-items: center;
    }
  }

  .pp {
    flex: 1;
    overflow-y: auto;

    .input {
      padding: 40rpx 0;
      display: flex;
      flex-wrap: wrap;
      gap: 20rpx;

      .item {
        border: 1px solid #f1f1f1;
        padding: 10rpx 20rpx;
        border-radius: 10rpx;
        color: #999999;

        &.active {
          background-color: $u-primary;
          color: #fff;
        }
      }
    }
  }

  .actions {
    padding-top: 40rpx;
    display: flex;
    gap: 20rpx;

    .item {
      flex: 1;
    }
  }
}
</style>
